/**  
 * @date 2023-11-24 
 * @author Zhang Yu
 */
package com.jwt.shiro.demo.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;

/**  
 * @description: jwt工具类
 */
public class JWTUtil {
	/**  
	 * TODO
	 */  
	
	private static final String USERNAME = "username";
	// 过期时间 24 小时
	private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;
	// 密钥
	private static final String SECRET = "SHIRO+JWT";
	

	/**
	 * @description: 创建token并且携带用户名
	 * @param username  用户名
	 * @return token
	 */
	public static String createToken(String username) {
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			return JWT.create().withClaim(USERNAME, username).withExpiresAt(date).sign(algorithm);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @description: 验证token是否正确
	 * @param token  token
	 * @param username 用户名
	 * @return 是否正确
	 */
	public static boolean verify(String token, String username) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTVerifier jwtVerifier = JWT.require(algorithm).withClaim(USERNAME, username).build();
			// 验证token
			jwtVerifier.verify(token);
			return true;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * @description: 获得token中的信息，无需secret解密也能获取
	 * @param token token
	 * @return 用户名
	 */
	public static String getUsername(String token) {
		DecodedJWT decodedJWT = JWT.decode(token);
		return decodedJWT.getClaim(USERNAME).asString();
	}

}
